package com.jtpay.unionpay.product;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.jtpay.unionpay.product.dbUtils.CustomDbUtils;
import com.jtpay.unionpay.product.http.ApiHelper;
import com.jtpay.unionpay.product.http.listener.TransApiResultListener;
import com.jtpay.unionpay.product.model.ProductBean;
import com.jtpay.unionpay.product.model.RemoteModel;
import com.jtpay.unionpay.product.service.RemoteDataService;
import com.jtpay.unionpay.product.service.UnionPayProductService;
import com.jtpay.unionpay.product.utils.LogUtil;
import com.jtpay.unionpay.product.utils.PollingUtils;
import com.jtpay.unionpay.product.utils.SharedPreferenceUtil;
import com.jtpay.unionpay.product.utils.manager.ToastUtil;

import static com.jtpay.unionpay.product.utils.ActivityHelper.openUnionPayService;
import static com.jtpay.unionpay.product.utils.ActivityHelper.startUnionPayMainActivity;
import static com.jtpay.unionpay.product.utils.PayContext.*;

public class MainActivity extends Activity {

    @SuppressLint("StaticFieldLeak")
    private static MainActivity instance;
    private TextView mTvLogView;
    private int count = 0;//log lines count
    private SharedPreferenceUtil mSharedPreferenceUtil = new SharedPreferenceUtil();
    private Handler mHandler;
    private MyRunnable mMyRunnable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        openAccessibilityServiceSettingIfNeed();
    }

    @Override
    protected void onDestroy() {
        log("MainActivity onDestroy");
        super.onDestroy();
    }

    public static MainActivity getInstance() {
        if (instance == null) {
            instance = new MainActivity();
        }
        return instance;
    }

    /**
     * init View
     */
    private void initView() {
        String versionName = Debug ? "(ce)" : "";
        setTitle(getString(R.string.union_pay) + versionName);
        ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            actionBar.setSubtitle(String.format("%s%s",
                    getString(R.string.version), BuildConfig.VERSION_NAME));
        }
        mTvLogView = findViewById(R.id.tv_log_content);
        mTvLogView.setMovementMethod(ScrollingMovementMethod.getInstance());
    }

    /**
     * init Data
     */
    private void initData() {
        instance = this;
        mHandler = new Handler();
        mMyRunnable = new MyRunnable();
        PollingUtils.getInstance().initPollingService(this, ALARM_POLLING_INTERVAL);
        CustomDbUtils.getInstance().initDBUtils(this);
        doRequestPermissions();
    }

    /**
     * test product
     *
     * @param view target view
     */
    public void testProduct(View view) {
        /*Intent intent = new Intent(this, RemoteDataService.class);
        PollingUtils.getInstance().startTimingService(intent);*/
        Intent intent = new Intent(this, RemoteDataService.class);
        startService(intent);
    }

    /**
     * start Product
     *
     * @param view target view
     */
    public void startProduct(View view) {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
//                startUnionPayMainActivity();
                getRemoteTask();
            }
        }, 500);
    }

    private void getRemoteTask() {
        if (!isAccessibilitySettingsOn(this)) {
            return;
        }
        ApiHelper.getInstance(this).getTaskAPI(new TransApiResultListener<RemoteModel>() {
            @Override
            public void trans(RemoteModel msg) {
                CustomDbUtils.getInstance().deleteAll();
                log(msg.toString());
                ProductBean bean = new ProductBean(
                        msg.getTradeMoney(), msg.getOrderId(), "0");
                CustomDbUtils.getInstance().insert(bean);
                startUnionPayMainActivity();
            }
        });
    }

    public void getUPAccountResult(String result) {
        LogUtil.log(result);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (!checkRequestPermissions()) {
            return false;
        }
        switch (item.getItemId()) {
            case R.id.cleanLog:
                mTvLogView.setText(getString(R.string.log_output));
                break;
            case R.id.cleanSPCache:
                mSharedPreferenceUtil.SP_CLEAN(this);
                log(getString(R.string.data_cache_all_clean));
                CustomDbUtils.getInstance().deleteAll();
                break;
            case R.id.cleanDb:
                CustomDbUtils.getInstance().deleteAll();
                break;
            case R.id.openAccessService:
                openAccessibilityServiceSetting();
                break;
            case R.id.openProgramSetting:
                openProgramSetting();
                break;
            case R.id.doUpload:
                break;
            case R.id.exit:
                android.os.Process.killProcess(android.os.Process.myPid());
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * open AccessibilityService Setting If Needed
     */
    private void openAccessibilityServiceSettingIfNeed() {
        if (isAccessibilitySettingsOn(this)) {
            return;
        }
        openUnionPayService();
        //查询是否服务开启成功
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!isAccessibilitySettingsOn(MainActivity.this)) {
                    showToast(getString(R.string.service_auto_open_fail_tips));
                }
            }
        }, 500);
    }

    /**
     * log show
     *
     * @param content log show content
     */
    public void log(final String content) {
        try {
            LogUtil.log(content);
            mMyRunnable.setContent(content);
            runOnUiThread(mMyRunnable);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param string show msg
     */
    private void showToast(String string) {
        log(string);
        ToastUtil.showShort(string);
    }

    private void openAccessibilityServiceSetting() {
        Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    private void openProgramSetting() {
        Intent intent = new Intent()
                .setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                .setData(Uri.fromParts("package", getPackageName(), null));
        startActivity(intent);
    }

    /**
     * isAccessibilitySettingsOn check service is opened
     *
     * @param context Context
     * @return check result
     */
    private boolean isAccessibilitySettingsOn(Context context) {
        int accessibilityEnabled = 0;
        final String service = getPackageName() + "/" + UnionPayProductService.class.getCanonicalName();
        try {
            accessibilityEnabled = Settings.Secure.getInt(context.getApplicationContext().getContentResolver(),
                    android.provider.Settings.Secure.ACCESSIBILITY_ENABLED);
        } catch (Settings.SettingNotFoundException e) {
            LogUtil.log("Error ，productService to not found: " + e.getMessage());
        }
        TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');
        if (accessibilityEnabled == 1) {
            LogUtil.log("***ACCESSIBILITY IS ENABLED*** -----------------");
            String settingValue = Settings.Secure.getString(context.getApplicationContext().getContentResolver(),
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            if (settingValue != null) {
                mStringColonSplitter.setString(settingValue);
                while (mStringColonSplitter.hasNext()) {
                    String accessibilityService = mStringColonSplitter.next();
                    if (accessibilityService.equalsIgnoreCase(service)) {
//                        log(getString(R.string.service_already_opened_tips));
                        return true;
                    }
                }
            } else {
                log(getString(R.string.service_not_opened_tips));
            }
        }

        return false;
    }

    @Override
    public void finish() {
//        super.finish();
        moveTaskToBack(true);
    }

    private void doRequestPermissions() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        checkRequestPermissions();
    }

    private boolean checkRequestPermissions() {
        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED
                || ActivityCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
            showToast(getString(R.string.permission_denied_error));
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    finish();
                }
            }, 500);
            return false;
        }
        return true;
    }

    private class MyRunnable implements Runnable {
        private String mContent;

        public void setContent(String content) {
            mContent = content;
        }

        @Override
        public void run() {
            count++;
            if (count == LOG_CLEAN_LINE) {
                mTvLogView.setText(String.format("%s\n", getString(R.string.log_output)));
                count = 0;
            }
            mTvLogView.append(mContent + "\n");
            int offset = mTvLogView.getLineCount() * mTvLogView.getLineHeight();
            if (offset > mTvLogView.getHeight()) {
                mTvLogView.scrollTo(0, offset - mTvLogView.getHeight());
            }
        }
    }
}
